import http from '../utils/request'

const BASE_URL = 'http://localhost:8080'

export const photoService = {
  // 获取轮播图数据
  getSlides: async () => {
    const slides = await http.get('/photo/slides')
    // 添加完整的图片URL
    return slides.map(slide => ({
      ...slide,
      imagePath: BASE_URL + slide.imagePath,
      user: {
        ...slide.user,
        avatarUrl: slide.user.avatarUrl.startsWith('http') ? slide.user.avatarUrl : BASE_URL + slide.user.avatarUrl
      }
    }))
  },

  // 获取图片列表
  getPhotos: async (page = 1, size = 10) => {
    const res = await http.get('/photo/list', { params: { page, size } })
    // 添加完整的图片URL
    return {
      ...res,
      list: res.list.map(photo => ({
        ...photo,
        imagePath: BASE_URL + photo.imagePath,
        user: {
          ...photo.user,
          avatarUrl: photo.user.avatarUrl.startsWith('http') ? photo.user.avatarUrl : BASE_URL + photo.user.avatarUrl
        }
      }))
    }
  },

  // 上传图片
  uploadPhoto: (options) => {
    return new Promise((resolve, reject) => {
        wx.uploadFile({
            url: BASE_URL + '/photo/upload',
            filePath: options.filePath,
            name: options.name,
            timeout: 300000,
            header: {
                'Authorization': `Bearer ${wx.getStorageSync('token')}`,
                'Accept': 'application/json'
            },
            success: (res) => {
                console.log('上传响应状态码:', res.statusCode);
                console.log('上传响应头:', res.header);
                console.log('上传响应数据:', res.data);

                if (res.statusCode !== 200) {
                    reject(new Error(`上传失败: HTTP ${res.statusCode}`));
                    return;
                }

                if (!res.data) {
                    reject(new Error('服务器返回空数据'));
                    return;
                }

                try {
                    const data = JSON.parse(res.data);
                    console.log('解析后的数据:', data);

                    if (data.code === 0 && data.data) {
                        const result = {
                            ...data.data,
                            imagePath: BASE_URL + data.data.imagePath
                        };
                        if (data.data.user) {
                            result.user = {
                                ...data.data.user,
                                avatarUrl: data.data.user.avatarUrl.startsWith('http') 
                                    ? data.data.user.avatarUrl 
                                    : BASE_URL + data.data.user.avatarUrl
                            };
                        }
                        resolve(result);
                    } else {
                        reject(new Error(data.message || '上传失败'));
                    }
                } catch (error) {
                    console.error('解析响应失败:', error);
                    console.error('原始响应数据:', res.data);
                    reject(new Error('服务器响应格式错误'));
                }
            },
            fail: (error) => {
                console.error('上传请求失败:', error);
                if (error.errMsg.includes('timeout')) {
                    reject(new Error('上传超时，请重试'));
                } else {
                    reject(error);
                }
            }
        })
    })
  },

  // 点赞
  likePhoto: (id) => {
    return http.post(`/photo/like/${id}`)
  },

  // 获取用户统计数据
  getUserStats: async (userId) => {
    const res = await http.get(`/user/stats/${userId}`)
    return res
  },

  // 获取用户照片列表
  getUserPhotos: async (userId, page = 1, size = 10) => {
    const res = await http.get(`/user/photos/${userId}`, {
      params: { page, size }
    })
    return {
      ...res,
      list: res.list.map(photo => ({
        ...photo,
        imagePath: BASE_URL + photo.imagePath
      }))
    }
  },

  // 删除照片
  deletePhoto: async (photoId) => {
    return http.delete(`/photo/${photoId}`)
  }
} 